<template>
  <div class="container">
    <el-card class="article-container">
      <!-- 搜索 -->
      <el-row>
        <el-col :span="18">
          <el-form ref="formData">
            <el-form :inline="true" :model="articleSearch">
              <el-form-item size="small" label="关键字">
                <el-input
                  v-model="articleSearch.keyword"
                  placeholder="根据文章标题搜索"
                />
              </el-form-item>
              <el-form-item size="small" label="状态">
                <el-select v-model="articleSearch.state" placeholder="请选择">
                  <el-option label="启用" value="1" />
                  <el-option label="禁用" value="0" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button size="small" @click="resetForm">清除</el-button>
                <el-button type="primary" size="small" @click="getArticleList"
                  >查询</el-button
                >
              </el-form-item>
            </el-form>
          </el-form>
        </el-col>
        <el-col :span="6" style="text-align: right">
          <el-button
            type="success"
            size="small"
            icon="el-icon-edit"
            @click="dialogVisible = true"
            >新增技巧</el-button
          >
        </el-col>
      </el-row>
      <!-- 提示消息 -->
      <el-alert
        show-icon
        :title="`数据一共 ${articlePage.total} 条`"
        :closable="false"
      />
      <!-- 表格 -->
      <el-table :data="articleList" width="100%">
        <el-table-column type="index" label="序号" width="80%" />
        <el-table-column
          prop="title"
          label="文章标题"
          :show-overflow-tooltip="true"
          width="400%"
        >
          <template slot-scope="scope">
            {{ scope.row.title }}
            <i
              v-if="scope.row.videoURL"
              class="el-icon-film"
              @click="playVideo(scope.row)"
            ></i>
          </template>
        </el-table-column>
        <el-table-column prop="visits" label="阅读数" width="100%" />
        <el-table-column prop="username" label="录入人" width="150%" />
        <el-table-column
          prop="createTime"
          :formatter="formateTime"
          label="录入时间"
          width="200%"
        />
        <el-table-column
          prop="state"
          :formatter="formateState"
          label="状态"
          width="100%"
        />
        <el-table-column prop="" label="操作" width="300%">
          <template slot-scope="{ row }">
            <el-button type="text" @click="previewArticle(row)">预览</el-button>
            <el-button type="text" @click="changeState(row)">{{
              row.state === 0 ? "启用" : "禁用"
            }}</el-button>
            <el-button
              type="text"
              :disabled="row.state === 0"
              @click="editArticle(row)"
              >修改</el-button
            >
            <el-button
              type="text"
              :disabled="row.state === 0"
              @click="deleteArticle(row)"
            >
              删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <el-pagination
          hide-on-single-page
          background
          layout="prev, pager, next, jumper"
          :current-page="articlePage.page"
          :page-size="articlePage.pagesize"
          :total="articlePage.total"
          @current-change="changePage"
        />
      </el-row>
    </el-card>
    <!-- 弹出层 -->
    <el-dialog
      title="新增文章"
      :visible="dialogVisible"
      width="800px"
      @close="handleClose"
    >
      <el-form
        ref="articleInfo"
        :model="articleInfo"
        :rules="rules"
        label-width="13%"
        size="small"
      >
        <el-form-item label="文章标题：" prop="title">
          <el-input
            v-model="articleInfo.title"
            placeholder="请输入文章标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章内容：" prop="articleBody">
          <!-- 富文本插件 -->
          <!-- <template> -->
          <quill-editor
            v-model="articleInfo.articleBody"
            ref="myQuillEditor"
            :options="editorOption"
            @blur="onEditorBlur($event)"
          >
          </quill-editor>
          <!-- </template> -->
        </el-form-item>
        <el-form-item label="视频地址：" prop="videoURL">
          <el-input
            v-model="articleInfo.videoURL"
            placeholder="请输入视频地址"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="btnOk">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 预览弹层 -->
    <el-dialog
      title="预览文章"
      :visible="preDialogVisible"
      width="800px"
      @close="preDialogVisible = false"
    >
      <el-container>
        <el-header>
          <h2>{{ articleInfo.title }}</h2>
          <span>{{ articleInfo.createTime | filterName }}</span>
          <span>超级管理员</span>
          <i class="el-icon-view"></i>
          <span>{{ articleInfo.visits }}</span>
        </el-header>

        <el-main v-html="articleInfo.articleBody"></el-main>
      </el-container>
    </el-dialog>
    <!-- 视频弹出层 -->
    <div class="popShow" v-if="videoShow">
      <div class="backgound">
        <div class="video">
          <i class="el-icon-close" @click="videoShow = false"></i>
          <video :src="videoURL" autoplay width="800px" height="500px"></video>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  list,
  changeState,
  add,
  remove,
  detail,
  update
} from '@/api/hmmm/articles'

import { quillEditor } from 'vue-quill-editor'
import * as Quill from 'quill'
import { ImageDrop } from 'quill-image-drop-module'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import '@/assets/quill.css'
import dayjs from 'dayjs'
Quill.register('modules/imageDrop', ImageDrop)

export default {
  components: {
    quillEditor
  },
  data () {
    return {
      videoURL: '',
      videoShow: false,
      articleSearch: {
        keyword: '',
        state: ''
      },
      articlePage: {
        page: 1,
        pagesize: 10,
        total: 0
      },
      pageLength: '',
      articleList: [], // 数据列表
      state: false,
      dialogVisible: false, // 弹出层
      preDialogVisible: false,
      articleInfo: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike', 'image', 'link'], // toggled buttons
            ['blockquote', 'code-block'],
            [{ list: 'ordered' }, { list: 'bullet' }]
          ],
          imageDrop: true
        },
        placeholder: ''
      },
      rules: {
        title: [
          { required: true, trigger: 'blur', message: '请输入文章标题！' }
        ],
        articleBody: [
          { required: true, trigger: 'blur', message: '请输入文章内容！' }
        ]
      },
      newState: '' // 文章状态
    }
  },
  filters: {
    filterName: function (value) {
      return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  created () {
    this.getArticleList()
  },
  computed: {},
  methods: {
    // 清空表单内容
    resetForm () {
      this.articleSearch = {
        keyword: '',
        state: ''
      }
      this.$refs.formData.resetFields()
      this.getArticleList()
    },
    // 获取表格数据列表
    async getArticleList () {
      if (
        this.articleSearch.keyword === '' &&
        this.articleSearch.state === ''
      ) {
        var { data } = await list(this.articlePage)
      } else if (
        this.articleSearch.keyword !== '' &&
        this.articleSearch.state === ''
      ) {
        var { data } = await list(
          {
            keyword: this.articleSearch.keyword
          },
          this.articlePage
        )
      } else {
        var { data } = await list(this.articleSearch, this.articlePage)
      }
      this.articleList = data.items
      this.articlePage.total = data.counts
      this.pageLength = data.items.length
      // console.log(this.articleList);
    },
    // 格式化状态
    formateState (row, column, cellValue, index) {
      return cellValue === 1 ? '已启用' : '已禁用'
    },
    // 改变文章状态
    async changeState (row) {
      try {
        if (row.state === 1) {
          this.newState = 0
        } else {
          this.newState = 1
        }
        await changeState({
          id: row.id,
          state: this.newState
        })
        this.$message.success('操作成功！')
        this.getArticleList()
      } catch (err) {
        console.log(err)
        this.$message.fail('操作失败，请稍后重试！')
      }
    },
    // 删除文章
    async deleteArticle (row) {
      try {
        await this.$confirm('是否确认删除?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await remove(row)
        if (this.pageLength === 1) {
          this.articlePage.page--
        }
        this.getArticleList()
        this.$message.success('操作成功！')
      } catch (err) {
        console.log(err)
        this.$message('操作失败，请稍后重试！')
      }
    },
    // 关闭弹出层
    handleClose () {
      this.dialogVisible = false
      this.articleInfo = {
        title: '',
        articleBody: '',
        videoURL: ''
      }
      this.$refs.articleInfo.resetFields()
    },
    // 监听富文本框事件
    onEditorBlur () {},
    // 预览文章
    async previewArticle (row) {
      const { data } = await detail(row)
      // console.log(data);
      this.articleInfo = data
      // console.log(this.articleInfo);
      this.preDialogVisible = true
    },
    // 提交表单
    async btnOk () {
      await this.$refs.articleInfo.validate()
      try {
        await this.$confirm('是否确认操作?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        if (this.articleInfo.id) {
          await update(this.articleInfo)
        } else {
          await add(this.articleInfo)
        }
        this.getArticleList()
        this.dialogVisible = false
      } catch (err) {
        console.log(err)
      }
    },

    // 转换时间格式
    formateTime (row, column, cellValue, index) {
      const time = dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
      return time
    },
    // 分页
    changePage (current) {
      this.articlePage.page = current
      this.getArticleList()
    },
    // 编辑弹层
    async editArticle (row) {
      this.dialogVisible = true
      const { data } = await detail(row)
      // console.log(data);
      this.articleInfo = data
    },
    // 视频弹出层
    playVideo (row) {
      this.videoShow = true
      this.videoURL = row.videoURL
      console.log(this.videoURL)
    }
  }
}
</script>

<style scoped>
.container {
  margin: 10px;
}
.el-alert {
  margin-bottom: 20px;
}
.el-form-item.el-form-item--small {
  padding-left: 30px;
}
.el-header {
  border-bottom: 1px dashed #ccc;
  padding-left: 10px !important;
}
.el-main {
  background-color: #f5f5f5;
  padding: 10px;
}
h2 {
  padding: 0;
  margin: 0 0 10px 0;
}
span {
  margin-right: 10px;
}
i {
  margin-right: 5px;
}
.el-icon-film {
  margin-left: 10px;
  color: blue;
  font-size: 17px;
}
/* .popShow {
  position: absolute;
  top: 0;
  left: 0;
} */
.backgound {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: rgba(0, 0, 0, 0.3);
}
.video {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  object-fit: contain;
}
.el-icon-close {
  position: absolute;
  top: -14%;
  left: 50%;
  transform: translateX(-50%);
  width: 50px;
  height: 50px;
  border-radius: 50%;
  font-size: 20px;
  color: #fff;
  text-align: center;
  line-height: 50px;
  background: rgba(0, 0, 0, 0.4);
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.4);
}
</style>
